package car.aistar.controller;

import car.aistar.dto.Result;
import car.aistar.service.SendSms;
import com.alibaba.druid.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName SmsApiController
 * @Description TODO 发送验证码，发送之后验证，页面提交手机号和验证码发送到后台-从redis中根据手机号取出验证码校验，成功则登录成功
 * @Author laoxu
 * @Date 2020/10/15 18:43
 * Version 1.0
 **/

@RestController
@CrossOrigin //跨域支持
@RequestMapping("/send")
public class SmsApiController {

    @Autowired
    private SendSms sendSms;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/{phone}")
    public Result code(@PathVariable("phone") String phone){
        //模拟业务（redis）
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return new Result("400","验证码未过期");
        }

        //生成验证码并存储到redis中
        code = "";
        for (int i = 0; i<4; i++){
            code += (int)Math.floor(Math.random()*10);
        }
//        code = UUID.randomUUID().toString().substring(0,4);
        HashMap<String,Object> param = new HashMap<>();
        param.put("code",code);

        boolean isSend = sendSms.send(phone,"SMS_204455878",param);

        //生成并存储成功
        if (isSend){
            redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
            return new Result("200","验证码发送成功");
        }else {
            return new Result("500","发送失败");
//            return "发送失败！";//生成并存储失败
        }
    }
    @GetMapping("/{phone}/{code}")
    public Result demo(@PathVariable("phone") String phone,@PathVariable("code") String code){
        //前台获取的用户输入验证码与服务器端生成的验证码比较

        ValueOperations vop = redisTemplate.opsForValue();
        String code2 = (String) vop.get(phone);//后台存入redis的验证码
        if (code.equals(code2)){
            return new Result("200","验证码通过");
        }else {
            return new Result("500","验证码错误");
        }

    }
}
